<?php

namespace jjl\yii2\db;

use Yii;
use jjl\yii2\db\User;

trait LogTrait {

    public function attributeLabels() {
        return [
            'createAt' => Yii::t('db', 'Create At'),
            'createBy' => Yii::t('db', 'Create By'),
            'updateAt' => Yii::t('db', 'Update At'),
            'updateBy' => Yii::t('db', 'Update By'),
        ];
    }

    public function getCreateBy() {
        if ($this->id && ($model = Yii::$app->dbLog->mapping(static::class)->findOne("id = {$this->id} and type = 'insert'")))
            return User::findIdentity($model->operator);
        else
            return null;
    }

    public function getCreateAt() {
        if ($this->id && ($model = Yii::$app->dbLog->mapping(static::class)->findOne(['id' => $this->id, 'type' => 'insert'])))
            return $model->time;
        else
            return null;
    }

    public function getUpdateBy() {
        if ($this->id && ($model = Yii::$app->dbLog->mapping(static::class)->findOne("id = {$this->id} and type = 'update' order by time desc")))
            return User::findIdentity($model->operator);
        else
            return null;
    }

    public function getUpdateAt() {
        if ($this->id && ($model = Yii::$app->dbLog->mapping(static::class)->findOne("id = {$this->id} and type = 'update' order by time desc")))
            return $model->time;
        else
            return null;
    }

}
